package com.example.redis.autoregister.support;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.StringUtils;

public class BeanCacheKeyRedisSerializer implements RedisSerializer<Long> {
    private final String preKey;

    public BeanCacheKeyRedisSerializer(Class targetClass, String preKey) {
        this.preKey = StringUtils.isEmpty(preKey) ?  getDefaultPreKey(targetClass) : preKey;
    }

    /**
     * 获取默认的 key 前缀
     * @param beanClass
     * @return
     */
    private String getDefaultPreKey(Class beanClass){
        StringBuilder stringBuilder = new StringBuilder(beanClass.getSimpleName());
        stringBuilder.append(":");
        return stringBuilder.toString();
    }


    @Override
    public byte[] serialize(Long aLong) throws SerializationException {
        String key = this.preKey + aLong;
        return key.getBytes();
    }

    @Override
    public Long deserialize(byte[] bytes) throws SerializationException {
        String key = new String(bytes);
        return Long.valueOf(key.replace(this.preKey, "").trim());
    }
}
